package org.xjtu.weteam.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xjtu.weteam.common.utils.TokenUtils;
import org.xjtu.weteam.common.utils.imageUtil;
import org.xjtu.weteam.mapper.DictionaryMapper;
import org.xjtu.weteam.mapper.TeamMapper;
import org.xjtu.weteam.model.domain.Team;
import org.xjtu.weteam.model.dto.TeamDTO;
import org.xjtu.weteam.service.TeamService;

import java.io.IOException;
import java.util.List;

@Service
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService {
    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private DictionaryMapper dictionaryMapper;

    @Override
    public List<Team> getJoinTeams(String token) throws IOException {
        Integer userid  = TokenUtils.getIdFromToken(token);
        List<Team> teams =  teamMapper.selectJoinTeams(userid);
        for(int i=0;i<teams.size();i++){
            Team one = teams.get(i);
            one.setImagePath(imageUtil.getAvatar(one.getImagePath()));
            teams.set(i, one);
        }
        return teams;
    }

    @Override
    public void deleteTeam(Integer teamId) {
        teamMapper.deleteTeam(teamId);
    }

    @Override
    public Team getByTeamId(Integer teamId) {
        Team team =teamMapper.selectById(teamId);
        if (team!=null){
            try {
                team.setImagePath(imageUtil.getAvatar(team.getImagePath()));
            }catch (IOException e){}
        }
        return team;
    }

    @Override
    public boolean checkIfJoin(TeamDTO teamDTO) {
        Integer userId = TokenUtils.getIdFromToken(teamDTO.getToken());
        int t =teamMapper.checkIfJoin(userId,teamDTO.getTeamId());
        if (t == 0){
            try {
                String role = dictionaryMapper.dictionaryCodeSearchById(10);
                teamMapper.insertUserTeam(userId,teamDTO.getTeamId(),role);
                return false;
            }catch (Exception e){}
        }
        return true;
    }

    @Override
    public Boolean createTeam(Team team,String token) {
        Integer userId =TokenUtils.getIdFromToken(token);
        System.out.println("id: "+ userId);
        teamMapper.insertTeam(team);
        String role = dictionaryMapper.dictionaryCodeSearchById(9);
        teamMapper.insertUserTeam(userId,team.getTeamId(),role);
        return true;
    }
}
